package schoolmath.web.pages;

import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.tynamo.security.services.SecurityService;

public class Signin {

	private String login;
	private String password;
	@Inject
	private SecurityService securityService;
	@Persist(PersistenceConstants.FLASH)
	private String loginMessage;

	public String getLogin() {
		return this.login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Object onActionFromForm() {
		Subject currentUser = securityService.getSubject();

		if (login == null || login.equals("")) {
			loginMessage = "Логин не указан";
			return null;
		}

		if (password == null) {
			password = "";
		}

		UsernamePasswordToken token = new UsernamePasswordToken(login, password);
		token.setRememberMe(true);

		try {
			currentUser.login(token);
		} catch (UnknownAccountException e) {
			loginMessage = "Аккаунт не существует";
			return null;
		} catch (IncorrectCredentialsException e) {
			loginMessage = "Неверный пароль";
			return null;
		} catch (LockedAccountException e) {
			loginMessage = "Аккаунт заблокирован";
			return null;
		} catch (AuthenticationException e) {
			loginMessage = "Ошибка аутентификации";
			return null;
		}

		return Panel.class;
	}

	public String getLoginMessage() {
		return this.loginMessage;
	}

}
